export default {
	namespaced: true,
	state: () => ({
		adapterOpen: false,
		adapterState: {},
		devices: [],
		connectedDevices: JSON.parse(uni.getStorageSync("connectedDevices") || "{}"),
		messages: {}
	}),
	mutations: {
		/** 修改state 数据_测试
		 * 	payload.Name1 - state层级属性数据 如 user.info.score
		 * 	payload.data  - 赋值内容
		 *  payload.StorageName  - 缓存名称，有缓存时会开启缓存
		 *  payload.StorageData  - 缓存内容，已处理成JSON格式
		 * 	@param {object} payload  这是一个对象，包含属性名，赋值内容，缓存名、缓存内容
		 */
		ChangeAndSetStateData(state, payload) {
			// 解构出要修改的属性名
			const {
				Name1,
				data,
				StorageName,
				StorageData,
			} = payload;

			// 如果属性名存在多级，可以使用动态属性名来修改对应的值
			const levels = Name1.split('.');
			let currentState = state;
			for (let i = 0; i < levels.length - 1; i++) {
				currentState = currentState[levels[i]];
			}
			currentState[levels[levels.length - 1]] = data;

			// 根据StorageName参数来决定是否记录缓存
			if (StorageName) {
				uni.setStorageSync(StorageName, StorageData);
			}
		},
		UPDATE_DEVICE_ALIAS(state, {
			deviceId,
			aliasName
		}) {
			const dev = state.connectedDevices[deviceId];
			if (dev) {
				dev.aliasName = aliasName;
			}
			// 同时更新全局 devices 列表中对应项
			if (state.devices && state.devices.length) {
				const idx = state.devices.findIndex(d => d.deviceId === deviceId);
				if (idx !== -1) state.devices[idx].aliasName = aliasName;
			}
			uni.setStorageSync("connectedDevices", JSON.stringify(state.connectedDevices || {}));
		},
		SET_ADAPTER_OPEN(state, val) {
			state.adapterOpen = val
		},
		SET_ADAPTER_STATE(state, val) {
			state.adapterState = val
		},
		CLEAR_DEVICES(state) {
			state.devices = []
		},
		ADD_DEVICE(state, dev) {
			state.devices.push(dev)
		},
		ADD_CONNECTED_DEVICE(state, dev) {
			// state.connectedDevices[dev.deviceId] = dev;
			console.log(state.connectedDevices);


			// 正确写法（使用 Vue.set 触发响应式）：
			Vue.set(state.connectedDevices, dev.deviceId, dev);
			uni.setStorageSync("connectedDevices", JSON.stringify(state.connectedDevices || {}));
		},
		REMOVE_CONNECTED_DEVICE(state, id) {
			delete state.connectedDevices[id]
		},
		updateDeviceStatus(state, {
			deviceId,
			connected
		}) {
			const dev = state.devices.find(d => d.deviceId === deviceId);
			if (dev) {
				dev.connected = connected;
				dev.lastUpdateTime = Date.now();
			}
		},
		UPDATE_CONNECTION(state, {
			deviceId,
			connected
		}) {
			if (state.connectedDevices[deviceId]) {
				// 方式1：用Vue.set更新嵌套属性（推荐）
				Vue.set(state.connectedDevices[deviceId], 'connected', connected);
				// 同步本地存储（保持持久化）
				uni.setStorageSync("connectedDevices", JSON.stringify(state.connectedDevices));
			}
		},
		ADD_MESSAGE(state, {
			deviceId,
			data
		}) {
			if (!state.messages[deviceId]) state.messages[deviceId] = []
			state.messages[deviceId].push(data)
		}
	},
	getters: {
		/**
		 * 获取已连接设备（按连接状态排序：已连接的在前）
		 */
		getConnectedDevices: state => {
			// 直接使用 state 中的数据（已通过 mutation 同步到本地存储）
			const data = state.connectedDevices || {};
			console.log(data);
			// 转为数组并按 connected 排序（connected为true的在前）
			return Object.values(data).sort((a, b) => {
				if (a.connected && !b.connected) return -1;
				if (!a.connected && b.connected) return 1;
				return 0;
			});
		}
	}
}